﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using Kooboo.HtmlFunc.Function;
using Kooboo.HtmlFunc.Providers;

namespace Kooboo.HtmlFunc.Analysis.Visitors
{
    public class CustomVisitor : StartEndVisitor
    {
        public CustomVisitor(VisitorContext context)
            : base(context, FuncType.Custom)
        {
        }

        private IFuncTester _startCommentTester;
        protected override IFuncTester StartCommentTester
        {
            get
            {
                if (_startCommentTester == null)
                    _startCommentTester = new Testers.ParametricTester(this.Func.StartComment);
                return _startCommentTester;
            }
        }

        protected override object OnQualified(HtmlCommentNode startNode, HtmlCommentNode endNode)
        {
            throw new NotImplementedException();
        }

        public override void VisitCommentNode(HtmlCommentNode commentNode)
        {
            if (this.ValidateRule() &&
                this.StartCommentTester.IsMatch(commentNode))
            {
                var endNode = this.FindCommentEndNode(commentNode, false);
                var tester = (Testers.ParametricTester)this.StartCommentTester;

                // instance
                var custom = Provider.Factory.GetProvider<ICustom>();
                custom.NativeParameters = tester.NativeParameters;
                custom.StartNode = commentNode;
                custom.EndNode = endNode;
                this.Context.Result.Customs.Add(custom);

                if (endNode != null)
                {
                    // mark context
                    this.Context.Items[this.FuncType] = custom;
                    // mark
                    this.BreakCommentNode = endNode;
                }
            }
        }
    }
}
